﻿using QFramework;
using UnityEngine;

namespace SnakeGame
{
    internal interface ISnakeSystem : ISystem
    {
        void Create(int x, int y);
        void Update();
    }
    public class SnakeSystem : AbstractSystem, ISnakeSystem
    {
        private Snake mCurSnake;
        private IGridMapSystem mGridMap;
        protected override void OnInit() => mGridMap = this.GetSystem<IGridMapSystem>();
        private void OnDirInput(DirInputEvent e) => mCurSnake.GetMoveDir(e.hor, e.ver);
        /// <summary>
        /// 创建蛇
        /// </summary>
        void ISnakeSystem.Create(int x, int y)
        {
            if (mCurSnake == null)
            {
                mCurSnake = new Snake(PosUpdate, mGridMap.SetNodeRotation);
                this.RegisterEvent<DirInputEvent>(OnDirInput);
            }
            mCurSnake.CreateBody(x, y);
            mGridMap.SetNodeState(x, y, Node.E_State.Snake);
        }
        void ISnakeSystem.Update()
        {
            mCurSnake.Move();
            Debug.Log(mCurSnake.ToString());
        }
        private void PosUpdate(Vector2Int head)
        {
            Node headNode = mGridMap.GetNode(head.x, head.y);
            switch (headNode.State)
            {
                case Node.E_State.Wall:
                case Node.E_State.Snake:
                    this.SendEvent<GameOverEvent>();
                    break;
                default:
                    if (headNode.State == Node.E_State.Food)
                    {
                        mCurSnake.Bigger();
                        this.SendEvent<EatFoodEvent>();
                    }
                    else mGridMap.SetNodeState(mCurSnake.LastPos, Node.E_State.Blank);
                    mGridMap.SetNodeState(headNode, Node.E_State.Snake);
                    break;
            }
        }
    }
}